﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Communication
{
    public class UdpClientCommunicator : ICommunicator
    {
        private readonly IPEndPoint endpoint;

        public UdpClientCommunicator(IPEndPoint endpoint)
        {
            this.endpoint = endpoint;
        }

        #region ICommunicator Members

        public byte[] DoCommunicate(byte[] msg)
        {
            //throw new NotImplementedException();
            var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            client.Bind(endpoint);
            byte[] tmp = BitConverter.GetBytes(msg.Length);
            client.SendTo(tmp, 0, sizeof (int), SocketFlags.Partial, endpoint);
            client.SendTo(msg, sizeof (int), msg.Length, SocketFlags.None, endpoint);

            var data = new Byte[256];
            var ms = new MemoryStream();
            int bytesRead;
            while ((bytesRead = client.Receive(data, 0, data.Length, SocketFlags.None)) > 0)
                ms.Write(data, 0, bytesRead);

            var result = new byte[ms.Length];
            Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int) ms.Length);

			return result;
        }

        #endregion
    }
}